import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-form';
import CreateProduct from './component/CreateProduct';
import UpdateProduct from './component/UpdateProduct';
import {
  queryProduct,
  addProduct,
  updateProduct,
  removeProduct,
  queryChannel,
  // queryClassify,
} from '@/services/ant-design-pro/apis';
import { render } from 'react-dom';

const BizType = (props) => {
  const actionRef = useRef();
  const [selRows, setSelRows] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdteModalVisible] = useState(false);
  const [stepFormVals, setStepFormVals] = useState();
  const [exportModalVisible, handleExportModalVisible] = useState(false);
  const param = {};
  const [classifys, setClassifys] = useState([]);

  // useEffect(() => {
  //   queryClassify().then((val) => {
  //     setClassifys(val.data);
  //   });
  // }, []);

  const handleDel = async (record) => {
    Modal.confirm({
      title: '删除产品',
      content: '确认删除产品？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const hide = message.loading('正在删除');
        try {
          await removeProduct({ id: record.id });
          hide();
          message.success('删除成功');
          actionRef.current.reload();
        } catch (error) {
          hide();
          message.error('删除失败请重试！');
          return false;
        }
      },
    });
  };

  const handleAdd = async (value) => {
    const hide = message.loading('正在添加');
    try {
      await addProduct({ ...value });
      hide();
      handleModalVisible(false);
      message.success('添加成功');
      actionRef.current.reload();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败');
      return false;
    }
  };

  const handleUpdate = async (value) => {
    const hide = message.loading('正在配置');
    try {
      await updateProduct({ ...value });
      hide();
      handleUpdteModalVisible(false);
      setStepFormVals(undefined);
      message.success('配置成功');
      actionRef.current.reload();
    } catch (error) {
      hide();
      message.error('配置失败');
    }
  };

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInSearch: true,
      hideInForm: true,
      hideInTable: true,
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '产品编码是必须项',
          },
        ],
      },
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '产品名称是必须项',
          },
        ],
      },
    },
    {
      title: '产品图片',
      dataIndex: 'productImg',
      hideInSearch: true,
      render: (text, record) => (
        <img src={record.productImg} alt="产品图片" width="40px" height="40px" />
      ),
    },
    // {
    //   title: '产品图片',
    //   dataIndex: 'productPicture',
    //   hideInSearch: true,
    //   render: (text, record) => (
    //     <img src={`/product-picture/${text}`} alt="产品图片" width="40px" height="40px" />
    //   ),
    // },
    // {
    //   title: '商品类型',
    //   // dataIndex:'classifyId',
    //   dataIndex: 'typeName',
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: true,
    //         message: '商品类型是必须项',
    //       },
    //     ],
    //   },
    // },
    // {
    //   title: '商品渠道',
    //   dataIndex: 'channelName',
    //   //dataIndex: 'channelId',
    // },
    {
      title: '官网价格',
      dataIndex: 'productPrice',
      hideInSearch: true,
    },
    {
      title: '自己价格',
      dataIndex: 'ownPrice',
      hideInSearch: true,
    },
    {
      title: '渠道',
      dataIndex: 'channelId',
      hideInSearch: true,
    },
    {
      title: '分类',
      dataIndex: 'classifyId',
      hideInSearch: true,
    },
    {
      title: '所属品牌',
      dataIndex: 'brandId',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        PUTAWAY: {
          text: '上架',
          status: 'Success',
        },
        DELIST: {
          text: '下架',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setStepFormVals(record);
            handleUpdteModalVisible(true);
          }}
        >
          配置
        </a>,
        // <a
        //   key="delete"
        //   onClick={() => {
        //     handleDel(record);
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        params={param}
        headerTitle="产品列表"
        rowKey="id"
        request={queryProduct}
        rowSelection={{
          onChange: (_, selRows) => {
            setSelRows(selRows);
          },
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        search={{
          defaultCollapsed: false,
          optionRender: (searchConfig, formProps, dom) => [
            ...dom.reverse(),
            //   <Button
            //     key="out"
            //     onClick={() => {
            //       const values = searchConfig?.form?.getFieldsValue();
            //       handleExportModalVisible(true)
            //     }}
            //   >
            //     导出
            //   </Button>,
          ],
        }}
      ></ProTable>

      <CreateProduct
        createModalVisible={createModalVisible}
        handleModalVisible={() => {
          handleModalVisible(false);
        }}
        handCreate={() => {}}
        onSubmit={async (values) => {
          await handleAdd(values);
        }}
        classifys={classifys}
        onCancel={() => {
          handleModalVisible(false);
        }}
      >
        {/* <ProTable
                  type="form"
                  columns={columns}
                  form={{initialValues:{productStatus:"99",productType:"1",receiveType:"1"}}}
                  onSubmit={async (values)=>{
                       await handleAdd(values)
                  }}
                >
                </ProTable> */}
      </CreateProduct>

      {stepFormVals && Object.keys(stepFormVals).length ? (
        <UpdateProduct
          updateModalVisible={updateModalVisible}
          handleModalVisible={() => {
            handleUpdteModalVisible(false);
            setStepFormVals(undefined);
          }}
          onSubmit={async (values) => {
            await handleUpdate({ ...values, id: stepFormVals.id });
          }}
          classifys={classifys}
          onCancel={() => {
            handleUpdteModalVisible(false);
            setStepFormVals(undefined);
          }}
          values={stepFormVals}
        >
          {/* <ProTable
                  type="form"
                  columns={columns}
                  form={{initialValues:{
                      ...stepFormVals,
                      productStatus:stepFormVals.productStatus?stepFormVals.productStatus+"":null,
                      productType:stepFormVals.productType?stepFormVals.productType+"":null,
                      receiveType:stepFormVals.receiveType?stepFormVals.receiveType+"":null
                    }}}
                  onSubmit={async (values)=>{
                    await handleUpdate({...values,id:stepFormVals.id})
                  }}
                >
                </ProTable> */}
        </UpdateProduct>
      ) : null}
    </PageContainer>
  );
};

export default BizType;
